package com.gavel.parser;

import com.gavel.database.SQLExecutor;
import com.gavel.utils.StringUtils;
import com.mrobuy.jdvc.entity.HtmlCache;
import com.mrobuy.util.MD5Utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MYMROSkuParser implements SkuParser {

    private static final Pattern CODE_PATTERN = Pattern.compile("/([a-zA-Z])-([^\\.]*).html", Pattern.CASE_INSENSITIVE);


    public AttrTable attrTable(String html) {

        AttrTable attrTable = new AttrTable();

        if (StringUtils.isBlank(html)) {
            return attrTable;
        }

        Document doc = Jsoup.parse(html);
        if ( doc == null ) {
            return attrTable;
        }

        List<String> headers = new ArrayList<>();

        Elements leftTitles = doc.select("div#leftTable1 tr.pxTR td");
        for (Element title : leftTitles) {
            String _title = title.attr("title");
            if ( StringUtils.isBlank(_title) ) {
                _title = title.text().trim();
            }
            headers.add(_title);
        }


        Elements rightTitles = doc.select("div#rightTable1 tr.pxTR td");
        for (Element title : rightTitles) {
            String _title = title.attr("title");
            if ( StringUtils.isBlank(_title) ) {
                _title = title.text().trim();
            }
            headers.add(_title);
            attrTable.getHeaders().add(_title);
        }


        Elements leftTable2 = doc.select("div#leftTable2 tr.trsku2");

        for (int row = 0; row < leftTable2.size(); row++) {
            Element trsku2 = leftTable2.get(row);
            Elements tds = trsku2.select("td");
            for (int i = 0; i < tds.size(); i++) {
                Element td = tds.get(i);
                String value = null;
                Element dweight = td.selectFirst("span.dweight");
                if ( dweight!=null ) {
                    value = StringUtils.trim(dweight.text());
                } else {
                    value = td.text();
                }

                if ( StringUtils.isBlank(value) ) {
                    value = StringUtils.trim(td.attr("title"));
                }

                attrTable.put(row, headers.get(i), value);
            }
        }

        Elements rightTable2 = doc.select("div#rightTable2 tr.trsku2");
        for (int row = 0; row < rightTable2.size(); row++) {
            Element trsku2 = rightTable2.get(row);
            Elements tds = trsku2.select("td");
            for (int i = 0; i < tds.size(); i++) {
                Element td = tds.get(i);
                String value = null;
                Element dweight = td.selectFirst("span.dweight");
                if ( dweight!=null ) {
                    value = StringUtils.trim(dweight.text());
                } else {
                    value = td.text();
                }

                if ( StringUtils.isBlank(value) ) {
                    value = StringUtils.trim(td.attr("title"));
                }

                attrTable.put(row, headers.get(i + 2), value);
            }
        }





        return attrTable;
    }


    @Override
    public SkuItem parser(String url, String html) {

        if (StringUtils.isBlank(html)) {
            throw new RuntimeException("HTML为空, SKU解析失败");
        }

        Document doc = Jsoup.parse(html);
        if ( doc == null ) {
            throw new RuntimeException("HTML文档解析失败");
        }

        SkuItem skuItem = new SkuItem();
        skuItem.setUrl(url);
        skuItem.setType("MYMRO");


        Elements imgs = doc.select("div.xtu dd img");


        int pos = 1;
        for (Element img : imgs) {

            String  src = img.attr("src");
            if ( src!=null && src.startsWith("//") ) {
                src = "https:" + src;
            }

            String original = src;
            src = original.replace("/350/", "/800/");

            if (  StringUtils.isNotBlank(src) ) {
                skuItem.addProductPic(pos++, src, original);
            }

        }


        Element proDetailCon = doc.selectFirst(".content div.proDetailCon");
        if ( proDetailCon==null ) {
            throw new RuntimeException("SKU信息定位失败");
        }

        // 品牌主名称(标题前品牌)
        String brand =  StringUtils.trim(proDetailCon.selectFirst("h3 > span > a").text());
        skuItem.setBrand(StringUtils.trim(brand));

        // 标题
        Element name = proDetailCon.selectFirst("h3 > a");
        if ( name==null || StringUtils.isBlank(name.text()) ) {
            throw new RuntimeException("SKU标题定位失败");
        }
//        String skuName =  StringUtils.trim(name.text());
//        if ( skuName.startsWith(brand)) {
//            skuName =  StringUtils.trim(skuName.substring(brand.length()));
//        }
        skuItem.setTitle( StringUtils.trim(name.text()));


        // 类目 品牌
        Element crumb = doc.selectFirst("div.crumbs div.wrapper");
        if ( crumb ==null ) {
            throw new RuntimeException("SKU类目定位失败");
        }

        Elements items = crumb.select("a");
        if ( items==null || items.size() < 6 ) {
            throw new RuntimeException("SKU类目信息解析失败");
        }

        List<String> categories = new ArrayList<>();

        // 全部产品 > 个人防护 > 身体防护 > 季节类工作服 > 春秋工作服 > 博迪嘉 常规荧光防风防雨夹克（可脱卸内胆）GN410B（同款30件起订） > 博迪嘉 Bodyguard Workwear 博迪嘉 常规荧光防风防雨夹克（可脱卸内胆） GN410B-2XL
        StringBuilder catedesc = new StringBuilder();
        for (int j = 1; j < 4; j++) {
            catedesc.append( StringUtils.trim(items.get(j).text())).append("|");
            categories.add(StringUtils.trim(items.get(j).text()));
        }
        String category = StringUtils.trim(items.get(4).text());
        catedesc.append(category);
        categories.add(category);

        skuItem.setCategory(category);
        skuItem.setCategoryDesc(catedesc.toString());
        skuItem.setCategories(categories);
        skuItem.setProduct(StringUtils.trim(items.get(5).text().replace(brand, ""))); // 产品

        // 价格
        Element price = proDetailCon.selectFirst("div.price");
        if ( price!=null ) {
            price.remove();   // 移除price
        }

        // 移除目录页提示
        Element catelogPage = proDetailCon.selectFirst("div.catelog-page");
        if ( catelogPage!=null ) {
            catelogPage.remove();
        }


        // 产品描述
        Elements proDetailDivs = doc.select("div.proDetailDiv");
        for (Element proDetailDiv : proDetailDivs) {

            Element proDetailTit = proDetailDiv.selectFirst("div.proDetailTit");
            if ( proDetailTit!=null && "产品描述".equalsIgnoreCase(proDetailTit.text()) ) {
                Element box = proDetailDiv.selectFirst("div.box");
                if ( box!=null ) {
                    skuItem.setIntro(box.html());
                    break;
                }
            }
        }

        Elements fonts = proDetailCon.select("div font");

        // 产品页面(g类型）
        if ( fonts.size()==2 ) {

            skuItem.setBrand(fonts.get(0).text());

            Matcher matcher = CODE_PATTERN.matcher(name.attr("href"));
            if ( matcher.find()) {
                skuItem.setCode(matcher.group(2));
            }

            return skuItem;
        }

        /**
         * 订 货 号：5W8061
         * 品   牌：霍尼韦尔 Honeywell
         * 制造商型号： SHSL00202-42
         * 包装内件数：1双
         * 预计发货日： 停止销售
         */
        String code = fonts.get(0).text();
        String fullBrand = fonts.get(1).text();
        String model = fonts.get(2).text();
        String number = fonts.get(3).text();
        String fahuori = fonts.get(4).text();

        skuItem.setCode(code);

        // 品   牌
        skuItem.setBrandEn(StringUtils.trim(fullBrand.replace(brand, "")));

        // 型号
        skuItem.setModel(StringUtils.trim(model));
        skuItem.addAttr("制造商型号", model);
        skuItem.setFahuori(fahuori);

        //  规格表
        List<String> headers = new ArrayList<>();
        Elements titles = doc.select("div#rightTable1 tr.pxTR td");
        for (Element title : titles) {
            String _title = title.attr("title");
            if ( StringUtils.isBlank(_title) ) {
                _title = title.text().trim();
            }
            headers.add(_title);
        }

        Elements rightTable2 = doc.select("div#rightTable2 tr.trsku2");
        for (Element trsku2 : rightTable2) {
            Elements spans = trsku2.select("span.dweight");
            if ( spans==null || spans.size()==0 ) {
                continue;
            }

            Elements tds = trsku2.select("td");
            for (int i = 0; i < tds.size(); i++) {
                String value = "";
                Element td = tds.get(i);
                Element dweight = td.selectFirst("span.dweight");
                if ( dweight!=null ) {
                    value = StringUtils.trim(dweight.text());
                }

                if ( StringUtils.isBlank(value) ) {
                    value = StringUtils.trim(td.attr("title"));
                }

                skuItem.addAttr(headers.get(i), value);
            }
        }

        // 解析计量单位
        skuItem.setUnit(SpecUtils.unit(skuItem.attr("包装数量"), SpecUtils.GRAINGER_SPLIT));

        // 价格信息
        Element sales_price = doc.selectFirst("div#fixedRightTable2 tr#item_" + code.trim() + " span.sales_price");
        skuItem.setSalesPrice(NumberUtils.toFloat(sales_price.text()));
        skuItem.setOriginalPrice(NumberUtils.toFloat(sales_price.text()));

        Element original_price =  sales_price.parent().selectFirst("span.dweight");
        if ( original_price!=null ) {
            skuItem.setOriginalPrice(NumberUtils.toFloat(original_price.text()));
        }


        Elements proDetailTits = doc.select(".content div.proDetailTit");
        for (Element proDetailTit : proDetailTits) {
            if ( "产品规格".equalsIgnoreCase(proDetailTit.text()) ) {
                Elements specs =  proDetailTit.nextElementSibling().select("ul li");
                if ( specs!=null && specs.size()>0 ) {
                    for (Element spec : specs) {
                        String _text = spec.text();
                        if ( StringUtils.isBlank(_text) ) {
                            continue;
                        }
                        _text = _text.replace("：", ":");

                        String[] pair = _text.split(":");
                        if ( pair==null || pair.length==0 ) {
                            continue;
                        }

                        if ( pair.length==1 ) {
                            skuItem.addAttr(pair[0], ".");
                        } else if ( pair.length==2 ) {
                            skuItem.addAttr(pair[0], pair[1]);
                        }
                    }
                }
            }

            if ( "产品描述".equalsIgnoreCase(proDetailTit.text()) ) {

                //"产品特征、 用途"
                Element box =  proDetailTit.nextElementSibling().selectFirst("div.box");
                if ( box!=null && box.childNodeSize() > 0 ) {
                    for (Node node : box.childNodes()) {
                        if ( node instanceof TextNode) {
                            String _text = ((TextNode) node).text();
                            if ( StringUtils.isBlank(_text) ) {
                                continue;
                            }

                            _text = _text.replace("：", ":").trim();
                            if ( _text.startsWith("●") ) {
                                continue;
                            }

                            // 特殊符号去掉
                            _text = _text.replace("·", "");

                            String[] pair = _text.split(":");
                            if ( pair.length==1 ) {
                                skuItem.addDetail(pair[0]);
                            } else {
                                skuItem.addAttr(pair[0], StringUtils.trim(pair[1]));
                            }
                        }
                    }
                }

                Elements detailImgs =  proDetailTit.nextElementSibling().select("img");
                pos = 1;
                System.out.println("000000: "+ detailImgs.size());
                if ( detailImgs!=null && detailImgs.size()>0 ) {
                    for (Element img : detailImgs) {
                        String  src = img.attr("src");
                        if ( src!=null && src.startsWith("//") ) {
                            src = "https:" + src;
                        }
                        if ( StringUtils.isNotBlank(src) ) {
                            skuItem.addDetailPic(pos++, src);
                        }
                    }
                }
            }

            if ( "产品图片".equalsIgnoreCase(proDetailTit.text()) ) {
                Elements detailImgs =  proDetailTit.nextElementSibling().select("img");
                if ( detailImgs!=null && detailImgs.size()>0 ) {
                    for (Element img : detailImgs) {
//                        String  src = img.attr("src");
//                        if ( src!=null && src.startsWith("//") ) {
//                            src = "https:" + src;
//                        }
//                        if (  StringUtils.isNotBlank(src) ) {
//                            skuItem.addProductPic(pos++, src);
//                        }
                    }
                }
            }
        }

        return skuItem;
    }

    public static void main(String[] args) throws Exception {


        String url = "https://www.mymro.cn/u-11G3190.html";

        String id = MD5Utils.md5Hex(url);
        String suffix =  id.substring(id.length()-1);

        System.out.println( "[" + suffix + "][" + id + "]" + url);


        HtmlCache htmlCache = SQLExecutor.executeQueryBean("select * from htmlcache_" + suffix + "  where ID = ? ", HtmlCache.class, id);
        if ( htmlCache==null || htmlCache.getHtml()==null ) {
            return;
        }

        MYMROSkuParser parser = new MYMROSkuParser();
        try {
            SkuItem spuItem = parser.parser(url, htmlCache.getHtml());
            System.out.println(spuItem.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
